package util;

/**
 * 线程工具类
 *
 * @author wanglei
 * @date 2021/1/8
 */
public class ThreadUtil {

    /**
     * 根据线程名称获取线程
     *
     * @param threadName 线程名称
     * @author wanglei
     * @date 2021/1/8
     */
    public static Thread getThreadByName(String threadName) {
        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().equals(threadName)) {
                return t;
            }
        }
        return null;
    }

    /**
     * 通过线程id获得线程
     *
     * @param threadId 线程id
     * @author wanglei
     * @date 2021/1/11
     */
    public static Thread getThreadById(long threadId) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while (group != null) {
            Thread[] threads = new Thread[(int) (group.activeCount() * 1.2)];
            int count = group.enumerate(threads, true);
            for (int i = 0; i < count; i++) {
                if (threadId == threads[i].getId()) {
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }
}
